Package Question2_4

Source Code of Question2_4.Question

package Question2_4;

import CtCILibrary.LinkedListNode;

public class Question {

  public static LinkedListNode partition(LinkedListNode node, int x) {
    LinkedListNode beforeStart = null;
    LinkedListNode beforeEnd = null;
    LinkedListNode afterStart = null;
    LinkedListNode afterEnd = null;
   
    /* Partition list */
    while (node != null) {
      LinkedListNode next = node.next;
      node.next = null;
      if (node.data < x) {
        if (beforeStart == null) {
          beforeStart = node;
          beforeEnd = beforeStart;
        } else {
          beforeEnd.next = node;
          beforeEnd = node;
        }
      } else {
        if (afterStart == null) {
          afterStart = node;
          afterEnd = afterStart;
        } else {
          afterEnd.next = node;
          afterEnd = node;
        }
      } 
      node = next;
    }
   
    /* Merge before list and after list */
    if (beforeStart == null) {
      return afterStart;
    }
   
    beforeEnd.next = afterStart;
    return beforeStart;
  }
 
  public static void main(String[] args) {
    /* Create linked list */
    int[] vals = {1, 3, 7, 5, 2, 9, 4};
    LinkedListNode head = new LinkedListNode(vals[0], null, null);
    LinkedListNode current = head;
    for (int i = 1; i < vals.length; i++) {
      current = new LinkedListNode(vals[i], null, current);
    }
    System.out.println(head.printForward());
   
    /* Partition */
    LinkedListNode h = partition(head, 5);
   
    /* Print Result */
    System.out.println(h.printForward());
  }

}
 
TOP

Related Classes of Question2_4.Question

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.